# -*- coding utf-8 -*-
import ast
import os.path


class CNCheckHelper():
    # 待检测文本可能的编码方式列表
    VALID_ENCODING = ('utf-8', 'gbk')

    def _get_unicode_imp(self, value, idx=0):
        if idx < len(self.VALID_ENCODING):
            try:
                encoding = self.VALID_ENCODING[idx]
                res = value.decode(encoding)
                return res
            except UnicodeDecodeError:
                return self._get_unicode_imp(value, idx + 1)
        else:
            return None

    def _get_unicode(self, from_str):
        if isinstance(from_str, str):
            return from_str
        return self._get_unicode_imp(from_str)

    def is_any_chinese(self, check_str, is_strict=True):
        unicode_str = self._get_unicode(check_str)
        if unicode_str:
            c_func = any if is_strict else all
            param = ('\u4e00' <= char <= '\u9fff' for char in unicode_str)
            return c_func(param)
        return False


class CodeCheck(ast.NodeVisitor):
    def __init__(self):
        self.cn_checker = CNCheckHelper()

    def visit_Str(self, node):
        self.generic_visit(node)
        if self.cn_checker.is_any_chinese(node.s, True):
            print("line no: %d, column offset: %d, CN_Str: %s" % (node.lineno, node.col_offset, node.s))


if __name__ == '__main__':
    # cn_checker = CNCheckHelper()
    # check_str = "中文a"
    # ch_res = cn_checker.is_any_chinese(check_str.encode('utf-8'), False)
    # print(ch_res)
    project_dir = os.getcwd()
    for root, dirs, files in os.walk(project_dir):
        print(root, dirs, files)
        py_files = filter(lambda file: file.endswith('.py') and file != 'check_helper.py', files)
        checker = CodeCheck()
        for file in py_files:
            file_path = os.path.join(root, file)
            print("Checking: %s" % file_path)
            with open(file_path, 'r', encoding='utf-8') as f:
                check_str = f.read()
                root_node = ast.parse(check_str)
                checker.visit(root_node)
